import { createSlice } from "@reduxjs/toolkit";
import { clearCart } from "./cartReducer";

// 定义初始状态
// 尝试从本地存储获取用户信息，如果存在则解析，否则设置为null
const initialState = {
  userInfo: localStorage.getItem("userInfo")
    ? JSON.parse(localStorage.getItem("userInfo"))
    : null,
};

// 创建认证切片
const authSlice = createSlice({
  name: "auth",
  initialState,
  reducers: {
    // 设置用户凭证的操作
    setCredentials: (state, action) => {
      state.userInfo = action.payload;
      localStorage.setItem("userInfo", JSON.stringify(action.payload));
      // 检查用户信息是否正确设置
      if (state.userInfo) {
        console.log("用户信息已设置:", state.userInfo);
      } else {
        console.log("设置用户信息失败");
      }
    },
    // 登出用户的操作，清除用户信息
    logout: (state) => {
      state.userInfo = null;
      localStorage.removeItem("userInfo");
    },
  },
});

// 导出动作创建者
export const { setCredentials, logout } = authSlice.actions;

// 导出登出用户的thunk，该thunk会分发logout和clearCart操作
export const logoutUser = () => async (dispatch) => {
  dispatch(logout());
  dispatch(clearCart()); // 登出时清空购物车
};

// 导出登录用户的thunk，该thunk会分发setCredentials和clearCart操作
export const loginUser = (userData) => async (dispatch) => {
  dispatch(setCredentials(userData));
  dispatch(clearCart()); // 登录时清空购物车以处理新用户会话
};

// 导出认证切片的reducer
export default authSlice.reducer;